import axios from 'axios';
import Vue from 'vue';
// axios.defaults.baseURL = "api/";
axios.defaults.timeout = 100000;
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.defaults.baseURL = '/';
axios.interceptors.request.use(
  (config) => {
    // 防止缓存
    if (config.method === 'post' && config.headers['Content-Type'] !== 'multipart/form-data') {
      config.data = {
        ...config.data,
      };
    } else if (config.method === 'get') {
      config.params = {
        ...config.params,
      };
    }
    const token = sessionStorage.getItem('csrf');
    config.headers['csrftoken'] = token;
    return config;
  },
  (error) => {
    alert('请求服务器超时');
    return error;
  }
);

// http响应拦截器
axios.interceptors.response.use(
  (res) => {
    if (res.config.responseType === 'blob' || res.config.responseType === 'arraybuffer' || res.config.responseType === 'stream') {
      return res;
    }
    const data = res.data;
    // if (res.config.url.indexOf("WebAPI/uploadfile") !== -1) {
    //   return data;
    // }
    if (data.code && data.code === 200) {
      return data.data;
    }
    alert(data.msg);
    return Promise.reject(data.msg);
  },
  (error) => {
    let errmsg = '服务器响应错误';
    if (error.response) {
      switch (error.response.code) {
        case -1:
          errmsg = '请登录后操作';
          break;
      }
    }
    alert(errmsg);
    return Promise.reject(error.response ? error.response.data : '');
  }
);
Vue.prototype.$http = axios;
